﻿using Autofac;
using PLC.Interface.ActualDatas;
using PLC.Interface.BaseUsers;
using PLC.Interface.Stations;
using PLC.Interface.Variables;
using PLCWpfTest.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using YWM;

namespace PLCWpfTest.Common
{
    public static class DataCache
    {
        private static int _updateCounter;

        public static event Action<BaseUserResultDto> OnUpdateLoginUser;

        public static BaseUserResultDto LoginUserInfo { get; set; }

        public static IReadOnlyList<StationResultDto> Stations { get; set; }

        public static Dictionary<long, ObservableCollection<ActualDataDto>> LongDateModelPairs { get; } = new Dictionary<long, ObservableCollection<ActualDataDto>>();

        public static void UpdateLongDateModelPairs()
        {
            if (!CommunicationCache.Connected || LongDateModelPairs.Count == 0)
            {
                return;
            }
            if (_updateCounter < 60)
            {
                _updateCounter++;
                return;
            }
            _updateCounter = 0;
            DateTime now = DateTime.Now;
            List<ActualDataDto> actualDatas = new List<ActualDataDto>();
            foreach (long id in LongDateModelPairs.Keys)
            {
                ObservableCollection<ActualDataDto> values = LongDateModelPairs[id];
                if (CommunicationCache.LongVariablePairs.ContainsKey(id))
                {
                    if (values.Count > 11)
                    {
                        values.RemoveAt(0);
                    }
                    VariableResultDto variable = CommunicationCache.LongVariablePairs[id];
                    ActualDataDto actualData = new ActualDataDto
                    {
                        VariableId = id,
                        DisplayName = variable.DisplayName,
                        Value = variable.Value.ToDouble(),
                        CreationTime = now,
                    };
                    values.Add(actualData);
                    actualDatas.Add(actualData);
                }
            }
            Task.Factory.StartNew(async state =>
            {
                using (ILifetimeScope scope = YApp.BeginLifetimeScope())
                {
                    IActualDataAppService actualDataAppService = scope.Resolve<IActualDataAppService>();
                    List<ActualDataDto> actuals = (List<ActualDataDto>)state;
                    await actualDataAppService.Create(actuals);
                }
            }, actualDatas);
        }

        public static void UpdateLoginUser(BaseUserResultDto userInfo)
        {
            if (LoginUserInfo.Id == userInfo.Id)
            {
                LoginUserInfo = userInfo;
                OnUpdateLoginUser?.Invoke(userInfo);
            }
        }
    }
}
